//
//  SLPermissionSetVC.m
//  SlockApp
//
//  Created by 凯朱 on 2024/7/25.
//

#import "SLUpdateFirmVC.h"
#import "SLUpdateFirmView.h"
#import "SLUpdateInstallView.h"
#import "YQCacheManager.h"
@interface SLUpdateFirmVC (){
    NSString *_taskId;
}
@property (nonatomic, strong)UITableView *tableView;
@property (nonatomic, strong)SLUpdateFirmView *headView;
@property (nonatomic, strong)NSTimer *timer;
@property (nonatomic, strong)NSTimer *requestTimer;

@end

@implementation SLUpdateFirmVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setUpSubViews];
    if (_updateInfo) {
        [_headView refresSubViewWith:_updateInfo];
    }else{
        [self checkFirmVersion];
    }
}

-(void)setUpSubViews{
    self.title = kLocalString(@"Firmware update");
    [self.view addSubview:self.tableView];
    _headView = [SLUpdateFirmView viewFromXIB];
    _headView.frame = self.tableView.bounds;
    kWeakSelf(self);
    [_headView setBtnBlock:^(NSInteger index) {
        [weakself handleUpdateView:index];
    }];
    
    _tableView.tableHeaderView = _headView;
}

-(void)loadBridgeVersionData{
    NSString *url = [NSString stringWithFormat:@"/msl_user/getDevInfo/%@?timeout=2",kCurClickDevice.deviceNo];
    kWeakSelf(self);
    [ZKHttpManager getWithPath:url params:@{} finished:^(BOOL isSuccessed, id  _Nonnull result, NSString * _Nonnull code, NSString * _Nonnull message) {
        if (!isSuccessed) {
            [ZCTool hideLoadingOnKeyWindow];
            kShowToast(message);
            return;
        }
        //更新页面
        weakself.updateInfo = result[@"result"];
        [weakself checkIfNeedUpdate:weakself.updateInfo[@"version"]];
    }];
}


-(void)checkFirmVersion{
    //先获取硬件的固件版本号
    [ZCTool showLoadingOnKeyWindow];
    if ([kCurClickDevice.deviceCategory isEqualToString:@"2"]) {
        if (kSTRING(_updateInfo[@"version"]).length > 0) {
            [self checkIfNeedUpdate:_updateInfo[@"version"]];
        }else{
            [self loadBridgeVersionData];
        }
    }else{
        [[SLBluetoothManager sharedManager] getDeviceBaseInfo:^(id data) {
            [self checkIfNeedUpdate:data[@"version"]];
        }];
    }
}

#pragma mark -- 检测是否需要更新固件版本
-(void)checkIfNeedUpdate:(NSString *)version{
//    version = @"v01.00.04";
    //校验是否有新的固件版本
    kWeakSelf(self);
    [ZCTool checkUpdateInfo:version finish:^(BOOL needUpdate, id  _Nonnull updateInfo) {
        [ZCTool hideLoadingOnKeyWindow];
        if (needUpdate){
            self->_updateInfo = updateInfo;
        }else{
            weakself.headView.topContentLbl.text = version;
        }
        [weakself.headView refresSubViewWith:weakself.updateInfo];
    }];
}

-(void)handleUpdateView:(NSInteger )index{
    if (index == 1) {
        //已下载
        if ([_headView.downloadBtn.titleLabel.text isEqualToString:kLocalString(@"Start install")]) {
            [self showInstallAlertView];
        } else {
            [self downLoadFirmware];
        }
    } else if (index == 2) {
        [self.navigationController popViewControllerAnimated:YES];
    }
}

-(void)downLoadFirmware{
    if (_updateInfo == nil || _updateInfo[@"url"] == nil) {
        [ZCTool showLoadingOnKeyWindowWith:kLocalString(@"Unable to obtain the latest version download url")];
        return;
    }
    NSString *fileUrl = _updateInfo[@"url"];
    [ZCTool showLoadingOnKeyWindowWith:kLocalString(@"Downloading...")];
    [ZKHttpManager downloadFilesWithUrl:fileUrl finished:^(BOOL isSuccessed, id  _Nonnull result, NSString * _Nonnull code, NSString * _Nonnull message) {
        [ZCTool hideLoadingOnKeyWindow];
        if (!isSuccessed) {
            kShowToast(message);
            return;
        }
        [self->_headView refresSubViewWith:self->_updateInfo];
        [self showInstallAlertView];
    }];
}

-(void)uploadUpdateResult:(BOOL)isSuccess{
    NSDictionary *params = @{@"taskId":@"d96b44538dfb465e9a9007f03fed5679",
                             @"deviceId":kCurClickDevice.deviceId,
                             @"successOrFailure":kSTRING(@(isSuccess))};
    [ZKHttpManager postWithPath:@"/msl_user/SubmitReport" params:params finished:nil];
}

-(void)showInstallAlertView{
    SLUpdateInstallView *alertView = [SLUpdateInstallView viewFromXIB];
    [alertView showWithAnmation:self.view];
    kWeakSelf(self);
    [alertView setBtnBlock:^(NSInteger btnIndex) {
        [weakself startInstall];
    }];
}

//开始固件传输
#pragma mark -- 固件升级
-(void)startInstall{
    
    SLUpdateInstallView *alertView = [self.view viewWithTag:1001111];
    [alertView removeWithAnimation];
    //网关升级
    kWeakSelf(self);
    if ([kCurClickDevice.deviceCategory isEqualToString:@"2"]) {
        if (_updateInfo == nil) {
            return;
        }
        [ZCTool showLoadingOnKeyWindowWith:kLocalString(@"Updating...")];
        NSDictionary *params = @{@"deviceNo":kCurClickDevice.deviceNo,
                                 @"updateUrl":_updateInfo[@"url"]};
        [ZKHttpManager postWithPath:@"/msl_user/remoteUpdate" params:params finished:^(BOOL isSuccessed, id  _Nonnull result, NSString * _Nonnull code, NSString * _Nonnull message) {
            if (!isSuccessed) {
                [ZCTool hideLoadingOnKeyWindow];
                kShowToast(message);
                return;
            }
            //更新进度
            [weakself startTimer];
            self->_taskId = result[@"result"];
            //开始每隔3s获取一次设备信息
//            if (!weakself.timer) {
//                weakself.timer = [NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(checkUpdateProgress) userInfo:nil repeats:NO];
//                [weakself.timer fire];
//            }
        }];
        return;
    }
    
    //蓝牙锁升级
    NSURL *filePath = _headView.filePath;
    NSData *fileData = [NSData dataWithContentsOfURL:filePath];
    [ZCTool showLoadingOnKeyWindowWith:kLocalString(@"Updating...")];
    [self startRequestTimer];
    [[SLBluetoothManager sharedManager] startUpdateFirmwareWith:fileData finish:^(BOOL isSuccess,CGFloat progress, NSString *errormsg) {
        if (isSuccess && progress != 999) {
            //更新进度
            NSString *progressStr = [NSString stringWithFormat:@"%.0f%%\n%@",progress*100,kLocalString(@"Updating...")];
            [ZCTool updateLoadingOnKeyWindowWith:progressStr];
            [self startRequestTimer];
            return;
        }
        [self stopRequestTimer];
        [ZCTool hideLoadingOnKeyWindow];
        if (!isSuccess) {
            [self uploadUpdateResult:NO];
            kShowToast(errormsg);
            return;
        }
        [self->_headView updateWithFinish:self->_updateInfo[@"serverVersion"]];
        [[SLBluetoothManager sharedManager] disConnectPeripheral];
        [self uploadUpdateResult:YES];
    }];
}

- (void)checkResponse {
    [ZCTool hideLoadingOnKeyWindow];
    [self.requestTimer invalidate];
    self.requestTimer = nil;
}

- (void)startRequestTimer {
    [self stopRequestTimer];
    self.requestTimer = [NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(checkResponse) userInfo:nil repeats:YES];
}

- (void)stopRequestTimer {
    if (self.requestTimer) {
        [self.requestTimer invalidate];
        self.requestTimer = nil;
    }
}


#pragma mark -- 固定3分钟更新进度
-(void)startTimer{
    int over = 180;//180秒
    __block int timeout = over;
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1*NSEC_PER_SEC, 0); //每秒执行
    dispatch_source_set_event_handler(_timer, ^{
        if(timeout<=0){ //倒计时结束，关闭
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                [ZCTool hideLoadingOnKeyWindow];
                [self->_headView updateWithFinish:self->_updateInfo[@"serverVersion"]];
                [self uploadUpdateResult:YES];
                if (self.updateSuccessBlock) {
                    self.updateSuccessBlock();
                }
            });
        }else{
            dispatch_async(dispatch_get_main_queue(), ^{
                //更新进度
                CGFloat progress = (float)(over-timeout)/over;
                NSLog(@"%.2f",progress);
                NSString *progressStr = [NSString stringWithFormat:@"%.0f%%\n%@",progress * 100,kLocalString(@"Updating...")];
                [ZCTool updateLoadingOnKeyWindowWith:progressStr];
            });
            timeout--;
        }
    });
    dispatch_resume(_timer);
}


-(void)checkUpdateProgress{
    NSString *url = [NSString stringWithFormat:@"msl_user/remoteUpdateQuery/%@",_taskId];
    [ZKHttpManager postWithPath:url params:@{} finished:^(BOOL isSuccessed, id  _Nonnull result, NSString * _Nonnull code, NSString * _Nonnull message) {
        NSLog(@"==========> isSuccessed: %d, result: %@", isSuccessed, result);
        if (!isSuccessed) {
            return;
        }
        
    }];
}

-(void)hanldeUpdateProcess:(BOOL)isSuccess progress:(CGFloat)progress errormsg:(NSString *)errormsg{
    if (isSuccess && progress != 999) {
        //更新进度
        NSString *progressStr = [NSString stringWithFormat:@"%.0f%%\n%@",progress*100,kLocalString(@"Updating...")];
        [ZCTool updateLoadingOnKeyWindowWith:progressStr];
        return;
    }
    [ZCTool hideLoadingOnKeyWindow];
    if (!isSuccess) {
        [self uploadUpdateResult:NO];
        kShowToast(errormsg);
        return;
    }
    [self->_headView updateWithFinish:self->_updateInfo[@"serverVersion"]];
    [[SLBluetoothManager sharedManager] disConnectPeripheral];
    [self uploadUpdateResult:YES];
}

#pragma mark - ================<懒加载>===============
-(UITableView *)tableView{
    if (_tableView == nil) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, SafeAreaTopHeight,kScreenWidth,kScreenHeight-SafeAreaTopHeight-SafeAreaBottomHeight) style:UITableViewStyleGrouped];
        _tableView.backgroundColor = KClearColor;
    }
    return _tableView;
}


@end
